import { create, verify } from "djwt";
import { AuthErrors } from "../errors/AppError.ts";

const SECRET_KEY = Deno.env.get("JWT_SECRET") ?? "your-secret-key";
const key = await crypto.subtle.importKey(
  "raw",
  new TextEncoder().encode(SECRET_KEY),
  { name: "HMAC", hash: "SHA-256" },
  false,
  ["sign", "verify"]
);

export const jwt = {
  sign: async (payload: Record<string, unknown>) => {
    const iat = Math.floor(Date.now() / 1000);
    const exp = iat + 24 * 60 * 60;
    
    return await create(
      { alg: "HS256", typ: "JWT" },
      { ...payload, iat, exp },
      key
    );
  },
  
  verify: async (token: string) => {
    try {
      return await verify(token, key);
    } catch {
      throw AuthErrors.InvalidToken();
    }
  }
}; 